package com.moyo.web.app.controller;

import com.moyo.model.User;
import com.moyo.service.UserService;
import com.moyo.service.SysPermissionService;
import com.moyo.utils.JwtUtil;
import com.moyo.utils.PasswordUtil;
import com.moyo.web.common.security.RequirePermissions;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * APP端用户接口
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService = new UserService();
    private final SysPermissionService permissionService = new SysPermissionService();

    @PostMapping("/register")
    public Map<String, Object> register(@RequestParam String username,
                        @RequestParam String password,
                        @RequestParam(required = false) String phone,
                        @RequestParam(required = false) String email) {
        String encodedPwd = PasswordUtil.encode(password);
        User user = userService.register(username, encodedPwd, phone, email, 0L);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("message", "注册成功");
        result.put("data", user);
        return result;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String username,
                                @RequestParam String password) {
        Optional<User> userOpt = userService.login(username, password);
        Map<String, Object> result = new HashMap<>();
        if (userOpt.isPresent() && PasswordUtil.matches(password, userOpt.get().getPassword())) {
            User user = userOpt.get();
            String token = JwtUtil.generateToken(
                user.getId(),
                permissionService.getUserPermissionCodes(user.getId())
            );
            result.put("code", 0);
            result.put("message", "登录成功");
            result.put("data", Map.of(
                "token", token,
                "user", user
            ));
        } else {
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
            result.put("data", null);
        }
        return result;
    }

    @RequirePermissions("user:view")
    @GetMapping("/profile/{id}")
    public Map<String, Object> profile(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", user.isPresent() ? 0 : 404);
        result.put("message", user.isPresent() ? "查询成功" : "用户不存在");
        result.put("data", user.orElse(null));
        return result;
    }
}
